﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace YTSK.FrmKP
{
    /// <summary>
    /// 拆单开票
    /// </summary>
    public partial class FrmCD : Form
    {
        public Vouch.VouchToolBar voudefine;
        public FrmCD()
        {
            InitializeComponent();
            voudefine = new Vouch.VouchToolBar("salebill", this.groupBox1,this.toolStrip1,"拆单开票");
            voudefine.Init();
            this.Icon = YTSK.Properties.Resources.Fly;
            this.Text = string.Format("拆单开票---版本{0}-{1}-{2}",
                ServerConfig.Version.ToString("yyyyMMdd"), ServerConfig._company, ServerConfig.UserName);
            foreach (ToolStripItem bar in this.toolStrip1.Items)
            {
                if (bar.Text.Length > 0)
                { bar.Click += toolbar_click; }
            }
        }

        #region 工具栏事件
        private void toolbar_click(object sender, EventArgs e)
        {
            if (sender.GetType() != typeof(ToolStripButton)) { return; }
            var bt = (ToolStripButton)sender;
            var text = bt.Text;
            toolbar_click(text);
        }
        public void toolbar_click(string text)
        {
            voudefine._dg.LeftEdit();
            switch (text)
            {
                case "删行":
                    voudefine.DelRow();
                    break;
                case "拆行":
                    voudefine.Spin();
                    break;
                case "税控开票":
                    voudefine.VouchToFP_SK(this);
                    break;
                case "回写发票号":
                    VouchToFPHand();
                    break;
                case "退出":
                    this.Close();
                    break;
            }
        }
        #endregion 



        #region 回写发票号
        /// <summary>
        /// 回写发票号-直接回写
        /// </summary>
        private void VouchToFPHand()
        {
            try
            {
                var err = "";
                List<Dictionary<string, object>> list;
                var main = voudefine.GetVouchData(out err, out list);
                if (err.Length > 0) { MessageBox.Show(err);return; }
                if (list.Count == 0) { MessageBox.Show("没有找到待开具的数据"); return; }
                var url = string.Format("{0}/api/oms/Rd2SK/GetOneForKP?token={1}&ID={2}",
                    ServerConfig.ServerAddress, ServerConfig.GetToken(), voudefine._id);
                var val = Common.handleHttp.Get(url);
                var result = Common.handleJSON.DeserializeResult(val);
                if (result.result != 1) { MessageBox.Show("出错:" + result.resultdetail); return; }

                #region 检查
                var sk_dkp = result.Get<Model.SK_SalebillVouch>("main");
                var l_sks_dkp = result.GetList<Model.SK_SalebillVouchs_View>("details");
                var sk = main.ToObj<Model.SK_SalebillVouch>();
                var l_sks = list.ToList<Model.SK_SalebillVouchs_View>();
                for (int i = 0; i < l_sks.Count; i++)
                {
                    var t = l_sks[i];
                    sk.iTraceID = t.iTraceID.ObjToInt();
                    var t_sk_save = l_sks_dkp.FirstOrDefault(s => s.iTraceAutoID == t.iTraceAutoID);
                    if (t_sk_save == null)
                    {
                        err = string.Format("产品[{0}]发票已经开具，请重新开票", t.cInvName);
                        MessageBox.Show(err);
                        return;
                    }
                    if (t.iSumSale.ObjToDecimal() > t_sk_save.iSumSale.ObjToDecimal())
                    {
                        err = string.Format("产品[{0}-{1}-{2}]未开票金额[{3}]小于本次开票金额[{4}]，请重新开票",
                            t.cInvCode, t.cInvName,t.cInvStd, t_sk_save.iSumSale, t.iSumSale);
                        MessageBox.Show(err);
                        return;
                    }
                    if (t.iQuantity.ObjToDecimal() > t_sk_save.iQuantity.ObjToDecimal())
                    {
                        err = string.Format("产品[{0}-{1}-{2}]未开票金额[{3}]小于本次开票金额[{4}]，请重新开票",
                            t.cInvCode, t.cInvName, t.cInvStd, t_sk_save.iQuantity, t.iQuantity);
                        MessageBox.Show(err);
                        return;
                    }
                }
                #endregion

                #region 开票
                var fback = new FrmKP.FrmReturn_SK(sk, l_sks,"","",true);
                fback.ShowDialog();
                if(fback.bSuc)
                {
                    this.Close();
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
            //finally { this.show(); }
        }
        #endregion

        #region 税控开票
        /// <summary>
        /// 税控开票
        /// </summary>
        public void VouchToFP()
        {
            try
            {
                var err = "";
                List<Dictionary<string, object>> list;
                var main = voudefine.GetVouchData(out err, out list);
                if (err.Length > 0) { MessageBox.Show(err); return; }
                if (list.Count == 0) { MessageBox.Show("没有找到待开具的数据"); return; }

                var sk = main.ToObj<Model.SK_SalebillVouch>();
                var l_sks = list.ToList<Model.SK_SalebillVouchs_View>();


                var url = string.Format("{0}/api/oms/Rd2SK/GetOneForKP?token={1}&ID={2}",
                    ServerConfig.ServerAddress, ServerConfig.GetToken(), sk.iTraceID);
                var val = Common.handleHttp.Get(url);
                var result = Common.handleJSON.DeserializeResult(val);
                if (result.result != 1) { MessageBox.Show("出错:" + result.resultdetail); return; }

                #region 检查
                var sk_dkp = result.Get<Model.SK_SalebillVouch>("main");
                var l_sks_dkp = result.GetList<Model.SK_SalebillVouchs_View>("details");
                for (int i = 0; i < l_sks.Count; i++)
                {
                    var t = l_sks[i];
                    var t_sk_save = l_sks_dkp.FirstOrDefault(s => s.IDInventory == t.IDInventory);
                    if (t_sk_save == null)
                    {
                        err = string.Format("产品[{0}]发票已经开具，请重新开票", t.cInvName);
                        MessageBox.Show(err);
                        return;
                    }
                    if (t.iSumSale.ObjToDecimal() > t_sk_save.iSumSale.ObjToDecimal())
                    {
                        err = string.Format("产品[{0}-{1}-{2}]未开票金额[{3}]小于本次开票金额[{4}]，请重新开票",
                            t.cInvCode, t.cInvName, t.cInvStd, t_sk_save.iSumSale, t.iSumSale);
                        MessageBox.Show(err);
                        return;
                    }
                    if (t.iQuantity.ObjToDecimal() > t_sk_save.iQuantity.ObjToDecimal())
                    {
                        err = string.Format("产品[{0}-{1}-{2}]未开票金额[{3}]小于本次开票金额[{4}]，请重新开票",
                            t.cInvCode, t.cInvName, t.cInvStd, t_sk_save.iQuantity, t.iQuantity);
                        MessageBox.Show(err);
                        return;
                    }
                    t.cInvCode = t_sk_save.cInvCode;
                    t.cInvName = t_sk_save.cInvName;
                    t.cInvStd = t_sk_save.cInvStd;
                    t.cDW = t_sk_save.cDW;
                    t.TaxCode= t_sk_save.TaxCode;
                }
                #endregion


                url = string.Format("{0}/api/oms/Rd2SK/GetOneForKPTry?token={1}&id={2}",
                    ServerConfig.ServerAddress, ServerConfig.GetToken(), sk.iTraceID);
                var resultval = Common.handleHttp.Get(url);
                result = Common.handleJSON.DeserializeResult(resultval);
                if (result.result != 1) { MessageBox.Show(result.resultdetail); return; }
                var b_dzfp = result.value["bYKP"].ObjToBool();
                #region 电子发票开具
                if (b_dzfp == true)
                {
                    url = string.Format("{0}/api/oms/Rd2SK/SetWeb_SK?token={1}",
                    ServerConfig.ServerAddress, ServerConfig.GetToken());
                    var dicpost = new Dictionary<string, object>();
                    dicpost.Add("main", sk);
                    dicpost.Add("detail", l_sks);
                    var poststr = Common.handleJSON.Serialize(dicpost);

                    resultval = Common.handleHttp.Post(poststr, url);
                    result = Common.handleJSON.DeserializeResult(resultval);
                    if (result.result != 1) { MessageBox.Show(result.resultdetail); return; }
                    sk = result.Get<Model.SK_SalebillVouch>("main");
                    var ftip = new FrmTip();
                    ftip.Show();
                    var isecond = 0;
                    while (isecond < 20)
                    {
                        ftip.setValue("电子发票开票请求已经发送，正在等待开票结果，请稍侯...", isecond);
                        System.Threading.Thread.Sleep(500);
                    }
                    ftip.Close();
                    url = string.Format("{0}/api/oms/Rd2SK/GetFPStatusSK?token={1}&id={2}",
                    ServerConfig.ServerAddress, ServerConfig.GetToken(), sk.ID);
                    resultval = Common.handleHttp.Get(url);
                    result = Common.handleJSON.DeserializeResult(resultval);
                    if (result.result != 1) { MessageBox.Show(result.resultdetail); }
                    else
                    {
                        MessageBox.Show(result.resultdetail);
                    }
                    this.Close();
                }
                #endregion
                #region 纸质发票
                else
                {
                    sk.cBillType = sk_dkp.cBillType;
                    err= cSK.SoftSel.proc(sk, l_sks);
                    if (err.Length > 0) { MessageBox.Show(err); }
                    this.Close();
                }
                #endregion 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
            finally { this.Show(); }
        }
        #endregion

        #region 显示数据
        public void Reflesh(int id)
        {
            try
            {
                var url = string.Format("{0}/api/oms/Rd2SK/GetOneForKP?token={1}&ID={2}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken(), id);
                var s = Common.handleHttp.Get(url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result != 1) { MessageBox.Show("出错:" + result.resultdetail); return; }

                #region 显示数据
                var sk = (Dictionary<string, object>)result.GetVal("main");
                voudefine._id = sk["ID"].ObjToInt();
                voudefine._ts = sk["ts"].ObjToString();
                var l_sks= result.GetListDic("details");
                voudefine.DisplayDataForm(sk);
                voudefine.Displaydata(l_sks, true);
                voudefine.SetToolBarEnable(true);
                foreach (ToolStripItem tool in this.toolStrip1.Items)
                {
                    tool.Enabled = true;
                }
                voudefine._bVouchModifyStatus = false;
                voudefine._dg.ReadOnly = false;
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion


    }
}
